package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(SystemConstants.HEAD_AUTHORIZATION);
        if (token == null) {
            return true;
        }
        // 查询redis
        String key = RedisConstants.LOGIN_USER_KEY + token;
        try {
            Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);
            if (map.isEmpty()){
                return true;
            }
            // 转为UserDTO
            UserDTO dto = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);
            //写入ThreadLocal
            UserHolder.saveUser(dto);
            // 刷新有效期
            stringRedisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.warn("Redis连接异常，无法获取用户信息，token: {}", token, e);
            // Redis异常时，允许请求继续执行（无用户状态）
            return true;
        }
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal中的用户信息，防止内存泄漏和线程间数据污染
        UserHolder.removeUser();
    }
}